/* eslint-disable vue/valid-v-for */
<template>
  <div class="main1">
    <a-col span="14">
      <a-form-model
        ref="showData"
        :model="showData"
        :label-col="{span:7}"
        :wrapper-col="{span: 16}"
        :rules="rules"
        class="user-layout-register">
        <!-- <a-form-model-item label="账号" prop="account" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.account"></a-input>
        </a-form-model-item> -->
        <a-form-model-item label="企业名称" prop="enterprise_name" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.enterprise_name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="工商注册号" prop="business_number" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.business_number" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="资质证书编号" prop="certificate_number" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.certificate_number"></a-input>
        </a-form-model-item>
        <a-form-model-item label="所属协会" prop="society_id" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-select v-model="showData.society_id" @change="jjz">
            <template v-for="(item, index) in societySelection">
              <a-select-option :key="index" :value="item.society_id">
                {{ item.society_name }}
              </a-select-option>
            </template>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="会员类别" prop="member_type" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-select v-model="showData.member_type" allowClear>
            <template v-for="(itemtype, index1) in membercenter">
              <a-select-option :key="index1" :value="itemtype.role_id">
                {{ itemtype.role_name }}
              </a-select-option>
            </template>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-alert message="注意请先选择所属协会再选择会员类别" type="info" show-icon style="width:295px;margin-left:12px"/>
        </a-form-model-item>
        <a-divider orientation="left" style="margin-top:0px">资质证书等级范围</a-divider>
        <a-form-model-item label="主项资质" prop="main_qualification" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-textarea v-model="showData.main_qualification" :autoSize="{ minRows: 3, maxRows: 5 }"></a-textarea>
        </a-form-model-item>
        <a-form-model-item label="副项资质" prop="minor_qualification" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-textarea v-model="showData.minor_qualification" :autoSize="{ minRows: 3, maxRows: 5 }"></a-textarea>
        </a-form-model-item>
        <a-divider></a-divider>
        <a-form-model-item label="企业地址" prop="business_address" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.business_address" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="邮政编号" prop="postcode" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.postcode" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="企业法人" prop="legal_person" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.legal_person" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="企业电话" prop="enterprise_tel" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model.number="showData.enterprise_tel" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="总经理" prop="president" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.president" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="经理电话" prop="president_tel" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model.number="showData.president_tel" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="联系人" prop="contacts" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.contacts" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="联系电话" prop="contacts_tel" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model.number="showData.contacts_tel" ></a-input>
        </a-form-model-item>
        <a-form-model-item label="职务" prop="password" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input v-model="showData.contact_title" ></a-input>
        </a-form-model-item>
        <!-- <a-form-model-item label="临时密码" prop="temporary_password" :style="{ display: 'inline-block', width: 'calc(50% - 12px)' }">
          <a-input-password v-model="showData.temporary_password" ></a-input-password>
        </a-form-model-item> -->
        <a-divider orientation="left">工商营业执照</a-divider>
        <a-form-model-item label="图片上传" :label-col="{span:'3'}" ref="upload1" :rules="[{ required: true, message: '图片不可为空', trigger: 'change'}]" prop="business_license_file">
          <a-upload
            :file-list="showData.business_license_file"
            :before-upload="beforeUpload"
            list-type="picture-card"
            accept="image/jpeg,image/jpg,image/png"
            :customRequest="(data) => {handleUpload(data, 'business_license_file')}"
            @preview="handlePreview"
            :remove="(file) => {handleRemove(file, 'business_license_file')}"
          >
            <a-button> <a-icon type="upload" /> 选择图片 </a-button>
          </a-upload>
        </a-form-model-item>
        <a-divider orientation="left">资质证书</a-divider>
        <a-form-model-item label="图片上传" :label-col="{span:'3'}" ref="upload2" :rules="[{ required: true, message: '图片不可为空', trigger: 'change'}]" prop="qualification_certificate_file">
          <a-upload
            :file-list="showData.qualification_certificate_file"
            :before-upload="beforeUpload"
            list-type="picture-card"
            accept="image/jpeg,image/jpg,image/png"
            :customRequest="(data) => {handleUpload(data, 'qualification_certificate_file')}"
            @preview="handlePreview"
            :remove="(file) => {handleRemove(file, 'qualification_certificate_file')}"
          >
            <a-button> <a-icon type="upload" /> 选择图片 </a-button>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 12, offset: 20}" >
          <a-button-group>
            <a-button @click="()=>{this.$router.push('/login')}">
              返回登陆页
            </a-button>
            <a-button type="primary" @click="onSubmit" :loading="loading">
              提交信息
            </a-button>
            <a-modal
              title=""
              :visible="visible"
              :confirm-loading="confirmLoading"
              :cancel-button-props="{ style: { display: 'none' } }"
              :closable="closable"
              @ok="confirm">
              <p>账号：{{ passaccount }}</p>
              <p>密码：{{ password }}</p>
            </a-modal>
          </a-button-group>
        </a-form-model-item>
      </a-form-model>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel" v-if="previewVisible">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-col>
  </div>
</template>

<script>
import md5 from 'md5'
import { getSmsCaptcha, Register, getSocietySelection, getMembertypeFinds, getSocietyCreatecc } from '@/api/login'
import { deviceMixin } from '@/store/device-mixin'
import { scorePassword } from '@/utils/util'
import { registerUpload } from '@/api/upload'
export default {
  name: 'Register',
  components: {
  },
  mixins: [deviceMixin],
  data () {
    return {
      password: {},
      passaccount: {},
      confirmLoading: false,
      closable: false,
      loading: false,
      visible: false,
      societySelection: [],
      membercenter: [],
      previewVisible: false, // 图片预览模态框可见
      previewImage: '', // 图片预览Src
      showData: { business_license_file: [], qualification_certificate_file: [], member_type: '' },
      registerBtn: false,
      rules: {
        enterprise_name: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        business_number: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        certificate_number: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        member_type: [
          { required: true, message: '内容不可为空', trigger: 'change' }
        ],
        main_qualification: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        business_address: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        legal_person: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        enterprise_tel: [
          { required: true, message: '内容不可为空', trigger: 'blur' },
          { type: 'number', message: '内容必须是数字' }
        ],
        contacts: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        contacts_tel: [
          { required: true, message: '内容不可为空', trigger: 'blur' },
          { type: 'number', message: '内容必须是数字' }
        ],
        president: [
          { required: true, message: '内容不可为空', trigger: 'blur' }
        ],
        president_tel: [
          { required: true, message: '内容不可为空', trigger: 'blur' },
          { type: 'number', message: '内容必须是数字' }
        ],
        society_id: [
          { required: true, message: '请选择所属协会', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
  },
  methods: {
    handleCancel () {
      this.previewVisible = false
      this.previewImage = ''
    },
    handlePreview (file) {
      this.previewImage = file.url
      this.previewVisible = true
    },
    // 上传图片Remove
    handleRemove (file, itemIndex) {
      console.log(file)
      const index = this.showData[itemIndex].indexOf(file)
      console.log(index)
      const newFileList = this.showData[itemIndex].slice()
      newFileList.splice(index, 1)
      this.showData[itemIndex] = newFileList
      // console.log(this.showData.domains[itemIndex].value)
    },
    // 上传图片before
    beforeUpload (file) {
      if (this.showData.society_id === undefined || this.showData.society_id === null) {
        this.$message.error('请先选择所属协会')
        return false
      }
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isLt3M) {
        this.$message.error('图片不得大于3MB')
        file.status = 'error'
      }
      return isLt3M
    },
    // 覆盖原有上传方法，自定义上传
    handleUpload (data, param) {
      console.log(data,param)
      var fd = new FormData()
      // this.showData.domains[index].value.forEach((item, itemIndex) => {
      //   fd.append(`file[${itemIndex}]`, item.originFileObj)
      // })
      // console.log(this.showData.domains[index].value)
      const file = {
        uid: '1',
        // thumbUrl: res.result[0].url,
        name: '1',
        status: 'uploading',
        response: '',
        url: ''
      }
      this.showData[param].push(file)
      // console.log(this.showData[param])
      fd.append('file[0]', data.file)
      fd.append('society_id', this.showData.society_id)
      // this.uploading = true
      registerUpload(fd).then(res => {
        if (res.code === 200) {
          this.$notification.success({
            message: '上传成功'
          })
          file.uid = res.result[0].file_id
          file.name = res.result[0].file_id
          file.status = 'done'
          file.response = ''
          file.url = res.result[0].url
          file.file_id = res.result[0].file_id
          file.society_id = ''
          file.array_id = ''
          // this.waitingUpload = res.result[0].url
          // this.showData.domains[index].value.push(file)
          if (param === 'business_license_file') {
            this.$refs.upload1.clearValidate()
          } else {
            this.$refs.upload2.clearValidate()
          }
          // data.onSuccess()
          // console.log(this.showData.domains[index].value)
          console.log(this.showData[param])
        } else {
          this.$notification.error({
            message: res.code,
            description: res.message
          })
          console.log(this.showData[param])
        }
        // this.uploading = false
      }).catch(err => {
        this.$notification.error({
           message: err.code,
          description: err.message
        })
        this.uploading = false
        console.log(err)
      })
    },
    handlePasswordLevel (rule, value, callback) {
      if (value === '') {
       return callback()
      }
      console.log('scorePassword ; ', scorePassword(value))
      if (value.length >= 6) {
        if (scorePassword(value) >= 30) {
          this.state.level = 1
        }
        if (scorePassword(value) >= 60) {
        this.state.level = 2
        }
        if (scorePassword(value) >= 80) {
        this.state.level = 3
        }
      } else {
        this.state.level = 0
        callback(new Error(this.$t('user.password.strength.msg')))
      }
      this.state.passwordLevel = this.state.level
      this.state.percent = this.state.level * 33

      callback()
    },

    handlePasswordCheck (rule, value, callback) {
      const password = this.form.getFieldValue('password')
      // console.log('value', value)
      if (value === undefined) {
        callback(new Error(this.$t('user.password.required')))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error(this.$t('user.password.twice.msg')))
      }
      callback()
    },

    handlePhoneCheck (rule, value, callback) {
      console.log('handlePhoneCheck, rule:', rule)
      console.log('handlePhoneCheck, value', value)
      console.log('handlePhoneCheck, callback', callback)

      callback()
    },

    handlePasswordInputClick () {
      if (!this.isMobile) {
        this.state.passwordLevelChecked = true
        return
      }
      this.state.passwordLevelChecked = false
    },

    handleSubmit () {
      const { form: { validateFields }, state, $router } = this
      validateFields({ force: true }, (err, values) => {
        if (!err) {
          state.passwordLevelChecked = false
          $router.push({ name: 'registerResult', params: { ...values } })
        }
      })
    },

    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state, $message, $notification } = this

      validateFields(['mobile'], { force: true },
        (err, values) => {
          if (!err) {
            state.smsSendBtn = true

            const interval = window.setInterval(() => {
              if (state.time-- <= 0) {
                state.time = 60
                state.smsSendBtn = false
                window.clearInterval(interval)
              }
            }, 1000)

            const hide = $message.loading('验证码发送中..', 0)

            getSmsCaptcha({ mobile: values.mobile }).then(res => {
              setTimeout(hide, 2500)
              $notification['success']({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.result.captcha,
                duration: 8
              })
            }).catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
          }
        }
      )
    },
    requestFailed (err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.registerBtn = false
    },
     onSubmit () {
      console.log(this.showData)
      // console.log(this.showData)
      this.$refs.showData.validate(valid => {
        if (valid) {
          this.loading = true
          console.log(this.showData)
          Register(this.showData).then(res => {
            this.visible = true
            this.showDates = JSON.parse(JSON.stringify(res))
            console.log(this.showDates)
            this.register_account = this.showDates.result.society_id
            this.register_password = this.showDates.result.membership_number
            this.membership = this.showDates.result.membership_id
            var accountj = this.showDates.result.society_id
            var accountk = this.showDates.result.membership_number
            if (accountj < 10) {
              accountj = '0' + accountj
              }
            if (accountk < 10) {
                accountk = '0' + '0' + accountk
              }
            if (accountk > 10 && accountk < 100) {
                accountk = '0' + accountk
              }
            this.passaccount = 'ment_' + accountj + accountk
            this.password = 'ment_' + accountj + accountk
            // this.showData.temporary_password = this.password
            if (res.code === 200) {
              this.$notification.success({
                title: '成功',
                message: '提交注册成功'
              })
              this.loading = false
            } else {
              this.loading = false
              this.$notification.error({
                message: '失败',
                description: res.message
              })
              this.showData.temporary_password = ''
            }
          }).catch(err => {
            this.$notification.error({
              title: err.code,
              message: err.message
            })
            this.loading = false
            this.showData.temporary_password = ''
          })
        }
      })
    },
    confirm () {
      this.confirmLoading = true
      this.$refs.showData.validate(valid => {
        if (valid) {
          var ggb = new FormData()
          ggb.append('society_id', this.register_account)
          ggb.append('membership_id', this.membership)
          ggb.append('account', this.passaccount)
          ggb.append('temporary_password', md5(this.password))
          getSocietyCreatecc(ggb).then(res => {
            console.log(ggb)
            this.$router.push('register-result')
          })
        }
      })
    },
    getSociety () {
      getSocietySelection().then(res => {
        this.societySelection = res.result
        console.log(this.societySelection)
      })
    },
    jjz (value) {
      this.showData.member_type = ''
      console.log(`${value}`)
      // eslint-disable-next-line camelcase
      var society_id = `${value}`
      console.log(this.showData.member_type)
      // localStorage.setItem('society_id', society_id)
      var sid = new FormData()
      sid.append('society_id', society_id)
      getMembertypeFinds(sid).then((res) => {
        this.membercenter = res.result
      })
    }
  },
  watch: {
    'state.passwordLevel' (val) {
      console.log(val)
    }
  },
  mounted () {
    this.getSociety()
  }
}
</script>
<style lang="less">
  .user-register {

    &.error {
      color: #ff0000;
    }

    &.warning {
      color: #ff7e05;
    }

    &.success {
      color: #52c41a;
    }

  }

  .user-layout-register {
    .ant-input-group-addon:first-child {
      background-color: #fff;
    }
  }
</style>
<style lang="less" scoped>
  .main1 {
    display: flex;
    justify-content: center;
  }
  .user-layout-register {

    & > h3 {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .getCaptcha {
      display: block;
      width: 100%;
      height: 40px;
    }

    .register-button {
      width: 50%;
    }

    .login {
      float: right;
      line-height: 40px;
    }
  }
</style>
